from .deploy import build_deploy_scheme
from ..extends.flask_sqlalchemy import db
from ..models import User
import click
import os


def register_commands(app):
    app.cli.add_command(build_deploy_scheme)

    @app.cli.command()
    @click.option('--drop', is_flag=True, help='Create after drop.')
    def init(drop):
        click.echo('初始化应用...')
        click.echo('初始化数据库...')
        # 初始化
        if drop:
            click.confirm('此操作将删除数据库,是否继续', abort=True)
            db.drop_all()
            click.echo('数据库删除成功')
        db.create_all()
        click.echo('初始化数据库成功')

        # 创建logs
        logs = os.path.join(app.root_path, '..', 'logs')
        if not os.path.exists(logs):
            click.echo('创建logs...')
            os.mkdir(logs)
            click.echo('logs创建成功')
        else:
            click.echo('logs文件存在，无需创建')

        # 创建public目录
        public = os.path.join(app.root_path, '..', 'public')
        if not os.path.exists(public):
            click.echo('创建public...')
            os.mkdir(public)
            click.echo('public创建成功')
        else:
            click.echo('public目录存在，无需创建')

        # 创建public/static目录
        static_path = os.path.join(public, 'static')
        if not os.path.exists(static_path):
            click.echo('创建public/static...')
            os.mkdir(static_path)
            click.echo('创建public/static成功')
        else:
            click.echo('public/static目录存在，无需创建')

        # 创建public/templates目录
        templates_path = os.path.join(public, 'templates')
        if not os.path.exists(templates_path):
            click.echo('创建public/templates...')
            os.mkdir(templates_path)
            click.echo('创建public/templates成功')
        else:
            click.echo('public/templates目录存在，无需创建')

        # 创建site.py文件
        site_py = os.path.join(public, 'site.py')
        if not os.path.exists(site_py):
            click.echo('创建site.py...')
            open(site_py, 'a').close()
            click.echo('创建site.py成功')
        else:
            click.echo('site.py存在，无需创建')

        click.echo('初始化应用完成')

    @app.cli.command()
    def create_super():
        account = click.prompt('请输入你的账号')
        if User.query.filter_by(account=account).first():
            click.echo('此账号已存在')
        else:
            with db.auto_commit():
                user = User()
                user.account = account
                user.password = '88888888'
                db.session.add(user)
            click.echo('密码：' + '88888888')
            click.echo('管理员创建成功!')
